package com.xxx.blog.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.xxx.blog.domain.ArticleType;
import com.xxx.blog.mapper.ArticleTypeMapper;
import com.xxx.blog.query.ArticleTypeQuery;
import com.xxx.blog.service.IArticleTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ArticleTypeServiceImpl implements IArticleTypeService {
    @Autowired
    private ArticleTypeMapper articleTypeMapper;

    @Override
    public List<ArticleType> findAll() {
        return articleTypeMapper.findAll();
    }

    @Override
    public ArticleType findOne(Long id) {
        return articleTypeMapper.findOne(id);
    }

    @Override
    public List<ArticleType> queryPage(ArticleTypeQuery articleTypeQuery) {
        PageHelper.startPage(articleTypeQuery.getCurrentPage(), articleTypeQuery.getPageSize());
        return articleTypeMapper.queryPage(articleTypeQuery);
    }

    @Override
    public void addArticleType(ArticleType articleType) {
        articleTypeMapper.addArticleType(articleType);
    }

    @Override
    public void updateArticleType(ArticleType articleType) {
        articleType.setUpdateTime(new Date());
        articleTypeMapper.updateArticleType(articleType);
    }

    @Override
    public void delete(Long id) {
        articleTypeMapper.delete(id);
    }

    @Override
    public void batchDeletes(Long[] ids) {
        articleTypeMapper.batchDeletes(ids);
    }

    @Override
    public List<ArticleType> getTypeTree(Long id) {
        List<ArticleType> articleTypes = articleTypeMapper.findAll();
        Map<Long, ArticleType> map = new HashMap<>();
        articleTypes.forEach(articleType -> map.put(articleType.getId(), articleType));
        // 遍历所有找自己的父类型：没有就直接加到类型树，有就找到自己的父类型，将自己加到父类型的集合中
        List<ArticleType> typeTree = new ArrayList<>();
        for (ArticleType articleType : articleTypes) {
            Long parentId = articleType.getParentId();
            if(id.equals(articleType.getId())) {
                continue;
            }
            if (parentId == null) {
                typeTree.add(articleType);
            } else {
                ArticleType parentArticleType = map.get(parentId);
                if (parentArticleType != null) {
                    List<ArticleType> children = parentArticleType.getChildren();
                    children.add(articleType);
                }
            }
        }
        return typeTree;
    }
}
